package day3.HomeWork;

/**
 * ClassName：TransferAccount
 *
 * @Author：小鱼
 * @Create：2025-08-20 22:22
 */
public class TransferAccount extends Thread{
    private Account from;
    private Account to;
    private double amount;

    public TransferAccount(String name,Account from, Account to, double amount) {
        super(name);
        this.from = from;
        this.to = to;
        this.amount = amount;
    }

    @Override
    public void run(){
        for (int i = 0; i < 5; i++) {
            transfer(this.from, this.to, this.amount);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void transfer(Account from,Account to,double amount){
        // 按账户名称字典序排序，确定加锁顺序（预防死锁）
        Account firstLock = from.getName().compareTo(to.getName()) <= 0 ? from : to;
        Account secondLock = from.getName().compareTo(to.getName()) <= 0 ? to : from;

        // 对两个账户加锁，保证操作原子性
        synchronized (firstLock) {
            synchronized (secondLock) {
                // 验证转出账户余额
                if (amount <= 0) {
                    System.out.println("转账金额必须大于0，转账失败");
                    return;
                }
                if (from.getBalance() < amount) {
                    System.out.printf("%s余额不足，无法转账%.2f元，当前余额:%.2f元%n",
                            from.getName(), amount, from.getBalance());
                    return;
                }

                // 执行转账操作
                from.decrease(amount);
                to.increase(amount);

                // 输出转账结果
                System.out.printf("%s：%s向%s转账%.2f元，%s余额:%.2f元，%s余额:%.2f元%n",
                        Thread.currentThread().getName(),
                        from.getName(), to.getName(), amount,
                        from.getName(), from.getBalance(),
                        to.getName(), to.getBalance());
            }
        }

        }
    }

